package com.example.scanidcard;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

 // 主页面类，用户可以上传身份证正反面图片，并进入结果页面进行识别。
public class MainActivity extends AppCompatActivity {
    // 请求码常量
    private static final int REQUEST_CODE_CAMERA = 1; // 拍照上传
    private static final int REQUEST_CODE_FILE = 2;   // 文件上传

    private ImageView frontImageView;  // 身份证正面图片
    private ImageView backImageView;   // 身份证反面图片
    private Button scanButton;

    // 文件用于保存正反面图片
    private File frontImageFile;
    private File backImageFile;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        frontImageView = findViewById(R.id.frontImageView);
        backImageView = findViewById(R.id.backImageView);
        scanButton = findViewById(R.id.scanButton);

        // 为正反面图片添加点击监听事件
        frontImageView.setOnClickListener(v -> showUploadOptions(true));
        backImageView.setOnClickListener(v -> showUploadOptions(false));

        // 扫描按钮点击事件，进入结果页面
        scanButton.setOnClickListener(v -> {
            if (frontImageFile != null && backImageFile != null) {
                Intent intent = new Intent(this, ResultActivity.class);
                intent.putExtra("frontImagePath", frontImageFile.getAbsolutePath());
                intent.putExtra("backImagePath", backImageFile.getAbsolutePath());
                startActivity(intent);
            } else {
                Toast.makeText(this, "请上传身份证正反面图片", Toast.LENGTH_SHORT).show();
            }
        });
    }

    // 选择图片上传方式：拍照或文件上传
    private void showUploadOptions(boolean isFront) {
        new android.app.AlertDialog.Builder(this)
                .setTitle("选择上传方式")
                .setItems(new String[]{"拍照上传", "文件上传"}, (dialog, which) -> {
                    if (which == 0) { // 拍照上传
                        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        startActivityForResult(cameraIntent, isFront ? REQUEST_CODE_CAMERA : REQUEST_CODE_CAMERA + 1);
                    } else { // 文件上传
                        Intent fileIntent = new Intent(Intent.ACTION_GET_CONTENT);
                        fileIntent.setType("image/*");
                        startActivityForResult(Intent.createChooser(fileIntent, "选择图片"), isFront ? REQUEST_CODE_FILE : REQUEST_CODE_FILE + 1);
                    }
                })
                .show();
    }

     @Override
     protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
         super.onActivityResult(requestCode, resultCode, data);
         if (resultCode == RESULT_OK && data != null) {
             try {
                 File outputFile = new File(getCacheDir(), (requestCode % 2 == 1 ? "front" : "back") + "_image.jpg");

                 // 处理文件上传（Uri）
                 if (data.getData() != null) {
                     Uri uri = data.getData();
                     InputStream inputStream = getContentResolver().openInputStream(uri);
                     writeFile(outputFile, inputStream);

                     if (requestCode == REQUEST_CODE_FILE) {
                         frontImageFile = outputFile;
                         frontImageView.setImageURI(uri);
                     } else if (requestCode == REQUEST_CODE_FILE + 1) {
                         backImageFile = outputFile;
                         backImageView.setImageURI(uri);
                     }
                 }
                 // 处理拍照上传（Bitmap）
                 else if (data.getExtras() != null && data.getExtras().get("data") instanceof android.graphics.Bitmap) {
                     android.graphics.Bitmap bitmap = (android.graphics.Bitmap) data.getExtras().get("data");
                     writeFile(outputFile, bitmap);

                     if (requestCode == REQUEST_CODE_CAMERA) {
                         frontImageFile = outputFile;
                         frontImageView.setImageBitmap(bitmap);
                     } else if (requestCode == REQUEST_CODE_CAMERA + 1) {
                         backImageFile = outputFile;
                         backImageView.setImageBitmap(bitmap);
                     }
                 }
             } catch (Exception e) {
                 e.printStackTrace();
                 Toast.makeText(this, "图片处理失败：" + e.getMessage(), Toast.LENGTH_SHORT).show();
             }
         }
     }

     // 将Bitmap保存为JPEG文件
     private void writeFile(File file, android.graphics.Bitmap bitmap) throws Exception {
         FileOutputStream outputStream = new FileOutputStream(file);
         bitmap.compress(android.graphics.Bitmap.CompressFormat.JPEG, 100, outputStream);
         outputStream.close();
     }


     private void writeFile(File file, InputStream inputStream) throws Exception {
        FileOutputStream outputStream = new FileOutputStream(file);
        byte[] buffer = new byte[1024];
        int length;
        while ((length = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, length);
        }
        outputStream.close();
        inputStream.close();
    }
}
